package cn.tpshion.config.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.tpshion.config.common.AssertUtil;
import cn.tpshion.config.service.support.AuthInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务类
 */
public class AuthService {

    private static final Logger log = LoggerFactory.getLogger(AuthService.class);

    private String host;

    private AuthInfo authInfo;

    /**
     * 配置中心认证，获取token
     */
    public String auth(){
        String url = host + "/auth/login";
        log.info("config doLogin request url:{} param:{}",url, JSONUtil.toJsonStr(authInfo));
        String result = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(authInfo))
                .execute().body();
        log.info("config doLogin response result:{}",result);
        String data = (String) checkResult(result);
        return data;
    }

    /**
     * 获取配置中心zookeeper地址
     * @param token
     * @return
     */
    public String getConfigHost(String token){
        AssertUtil.notEmpty(token,"token不能为空");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("token", token);
        String url = host + "/auth/getHost";
        log.info("getConfigHost request url:{} param:{}",url,paramMap);
        String result = HttpUtil.get(url, paramMap);
        log.info("getConfigHost response result:{}",result);
        String data = (String) checkResult(result);
        return data;
    }

    private Object checkResult(String result){
        AssertUtil.notEmpty(result,"请求配置中心失败");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String code = (String) jsonObject.get("code");
        AssertUtil.isTrue("00".equals(code),(String) jsonObject.get("msg"));
        return jsonObject.get("data");
    }

    public AuthService(String host, AuthInfo authInfo) {
        this.host = host;
        this.authInfo = authInfo;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public AuthInfo getAuthInfo() {
        return authInfo;
    }

    public void setAuthInfo(AuthInfo authInfo) {
        this.authInfo = authInfo;
    }
}
